using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos.AutoRenaming
{
    /// <summary>
    /// 照片自动重命名实体
    /// 支持基于多种规则的智能文件重命名功能
    /// </summary>
    public class PhotoAutoRenaming : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 照片ID
        /// </summary>
        public virtual Guid PhotoId { get; protected set; }

        /// <summary>
        /// 原始文件名
        /// </summary>
        [Required]
        [MaxLength(500)]
        public virtual string OriginalFileName { get; protected set; }

        /// <summary>
        /// 新文件名
        /// </summary>
        [MaxLength(500)]
        public virtual string NewFileName { get; protected set; }

        /// <summary>
        /// 重命名规则ID
        /// </summary>
        public virtual Guid? RuleId { get; protected set; }

        /// <summary>
        /// 重命名状态
        /// </summary>
        public virtual RenamingStatus Status { get; protected set; }

        /// <summary>
        /// 重命名类型
        /// </summary>
        public virtual RenamingType RenamingType { get; protected set; }

        /// <summary>
        /// 重命名优先级
        /// </summary>
        public virtual RenamingPriority Priority { get; protected set; }

        /// <summary>
        /// 重命名参数
        /// </summary>
        public virtual Dictionary<string, object> Parameters { get; protected set; }

        /// <summary>
        /// 重命名模式
        /// </summary>
        [MaxLength(1000)]
        public virtual string NamingPattern { get; protected set; }

        /// <summary>
        /// 重命名时间
        /// </summary>
        public virtual DateTime? RenamingTime { get; protected set; }

        /// <summary>
        /// 执行者ID
        /// </summary>
        public virtual Guid? ExecutorId { get; protected set; }

        /// <summary>
        /// 执行者名称
        /// </summary>
        [MaxLength(200)]
        public virtual string ExecutorName { get; protected set; }

        /// <summary>
        /// 是否预览模式
        /// </summary>
        public virtual bool IsPreviewMode { get; protected set; }

        /// <summary>
        /// 是否自动应用
        /// </summary>
        public virtual bool AutoApply { get; protected set; }

        /// <summary>
        /// 是否备份原文件
        /// </summary>
        public virtual bool BackupOriginal { get; protected set; }

        /// <summary>
        /// 备份路径
        /// </summary>
        [MaxLength(1000)]
        public virtual string BackupPath { get; protected set; }

        /// <summary>
        /// 冲突处理策略
        /// </summary>
        public virtual ConflictResolution ConflictResolution { get; protected set; }

        /// <summary>
        /// 重命名结果
        /// </summary>
        public virtual RenamingResult Result { get; protected set; }

        /// <summary>
        /// 重命名历史
        /// </summary>
        public virtual List<RenamingHistory> History { get; protected set; }

        /// <summary>
        /// 重命名规则
        /// </summary>
        public virtual RenamingRule Rule { get; protected set; }

        /// <summary>
        /// 照片导航属性
        /// </summary>
        public virtual Photo Photo { get; protected set; }

        protected PhotoAutoRenaming()
        {
            Parameters = new Dictionary<string, object>();
            Result = new RenamingResult();
            History = new List<RenamingHistory>();
        }

        public PhotoAutoRenaming(
            Guid id,
            Guid photoId,
            string originalFileName,
            RenamingType renamingType = RenamingType.Manual,
            Guid? ruleId = null,
            Guid? tenantId = null) : base(id)
        {
            PhotoId = photoId;
            OriginalFileName = originalFileName;
            RenamingType = renamingType;
            RuleId = ruleId;
            TenantId = tenantId;
            Status = RenamingStatus.Pending;
            Priority = RenamingPriority.Normal;
            ConflictResolution = ConflictResolution.AppendNumber;
            AutoApply = false;
            IsPreviewMode = true;

            Parameters = new Dictionary<string, object>();
            Result = new RenamingResult();
            History = new List<RenamingHistory>();
        }

        /// <summary>
        /// 生成新文件名
        /// </summary>
        public virtual void GenerateNewFileName(RenamingRule rule, Dictionary<string, object> context)
        {
            if (rule == null)
                throw new ArgumentNullException(nameof(rule));

            Rule = rule;
            NamingPattern = rule.Pattern;
            Parameters = context ?? new Dictionary<string, object>();

            try
            {
                var generatedName = ApplyNamingPattern(rule.Pattern, context);
                NewFileName = EnsureUniqueFileName(generatedName);

                AddHistory(RenamingAction.Generated, $"生成新文件名: {NewFileName}");
                Status = RenamingStatus.Generated;
            }
            catch (Exception ex)
            {
                Status = RenamingStatus.Failed;
                Result.ErrorMessage = ex.Message;
                AddHistory(RenamingAction.Failed, $"生成文件名失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 应用重命名
        /// </summary>
        public virtual void ApplyRenaming(Guid executorId, string executorName)
        {
            if (Status != RenamingStatus.Generated && Status != RenamingStatus.Preview)
                throw new InvalidOperationException($"无法在状态 {Status} 下应用重命名");

            ExecutorId = executorId;
            ExecutorName = executorName;
            RenamingTime = DateTime.Now;

            try
            {
                // 验证新文件名
                ValidateNewFileName();

                // 处理备份
                if (BackupOriginal)
                {
                    CreateBackup();
                }

                // 执行重命名
                ExecuteRenaming();

                Status = RenamingStatus.Completed;
                Result.IsSuccess = true;
                Result.NewFileName = NewFileName;
                Result.RenamingTime = RenamingTime.Value;

                AddHistory(RenamingAction.Applied, $"成功重命名为: {NewFileName}");
            }
            catch (Exception ex)
            {
                Status = RenamingStatus.Failed;
                Result.IsSuccess = false;
                Result.ErrorMessage = ex.Message;
                AddHistory(RenamingAction.Failed, $"重命名失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 预览重命名
        /// </summary>
        public virtual void PreviewRenaming(RenamingRule rule, Dictionary<string, object> context)
        {
            IsPreviewMode = true;
            GenerateNewFileName(rule, context);
            Status = RenamingStatus.Preview;
            AddHistory(RenamingAction.Previewed, $"预览重命名: {NewFileName}");
        }

        /// <summary>
        /// 取消重命名
        /// </summary>
        public virtual void CancelRenaming(string reason = null)
        {
            Status = RenamingStatus.Cancelled;
            Result.CancelReason = reason;
            AddHistory(RenamingAction.Cancelled, $"取消重命名: {reason}");
        }

        /// <summary>
        /// 撤销重命名
        /// </summary>
        public virtual void UndoRenaming()
        {
            if (Status != RenamingStatus.Completed)
                throw new InvalidOperationException($"无法在状态 {Status} 下撤销重命名");

            try
            {
                // 恢复原始文件名
                RestoreOriginalFileName();

                Status = RenamingStatus.Undone;
                Result.IsSuccess = false;
                AddHistory(RenamingAction.Undone, $"撤销重命名，恢复为: {OriginalFileName}");
            }
            catch (Exception ex)
            {
                AddHistory(RenamingAction.Failed, $"撤销重命名失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 更新重命名参数
        /// </summary>
        public virtual void UpdateParameters(Dictionary<string, object> parameters)
        {
            Parameters = parameters ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置冲突处理策略
        /// </summary>
        public virtual void SetConflictResolution(ConflictResolution resolution)
        {
            ConflictResolution = resolution;
        }

        /// <summary>
        /// 设置自动应用
        /// </summary>
        public virtual void SetAutoApply(bool autoApply)
        {
            AutoApply = autoApply;
        }

        /// <summary>
        /// 设置备份配置
        /// </summary>
        public virtual void SetBackupConfig(bool backup, string backupPath = null)
        {
            BackupOriginal = backup;
            if (!string.IsNullOrWhiteSpace(backupPath))
            {
                BackupPath = backupPath;
            }
        }

        /// <summary>
        /// 应用命名模式
        /// </summary>
        private string ApplyNamingPattern(string pattern, Dictionary<string, object> context)
        {
            var result = pattern;

            // 替换占位符
            result = ReplacePlaceholders(result, context);

            // 应用格式化规则
            result = ApplyFormattingRules(result);

            // 验证文件名
            result = ValidateAndCleanFileName(result);

            return result;
        }

        /// <summary>
        /// 替换占位符
        /// </summary>
        private string ReplacePlaceholders(string pattern, Dictionary<string, object> context)
        {
            var result = pattern;

            // 日期时间占位符
            result = ReplaceDateTimePlaceholders(result);

            // 照片属性占位符
            result = ReplacePhotoPlaceholders(result, context);

            // 自定义占位符
            result = ReplaceCustomPlaceholders(result, context);

            // 序列号占位符
            result = ReplaceSequencePlaceholders(result, context);

            return result;
        }

        /// <summary>
        /// 替换日期时间占位符
        /// </summary>
        private string ReplaceDateTimePlaceholders(string pattern)
        {
            var now = DateTime.Now;
            var result = pattern;

            // 基本日期时间格式
            result = result.Replace("{YYYY}", now.ToString("yyyy"));
            result = result.Replace("{YY}", now.ToString("yy"));
            result = result.Replace("{MM}", now.ToString("MM"));
            result = result.Replace("{DD}", now.ToString("dd"));
            result = result.Replace("{HH}", now.ToString("HH"));
            result = result.Replace("{mm}", now.ToString("mm"));
            result = result.Replace("{ss}", now.ToString("ss"));

            // 扩展日期格式
            result = result.Replace("{Date}", now.ToString("yyyy-MM-dd"));
            result = result.Replace("{Time}", now.ToString("HH-mm-ss"));
            result = result.Replace("{DateTime}", now.ToString("yyyy-MM-dd_HH-mm-ss"));
            result = result.Replace("{Timestamp}", ((long)(now - new DateTime(1970, 1, 1)).TotalSeconds).ToString());

            return result;
        }

        /// <summary>
        /// 替换照片属性占位符
        /// </summary>
        private string ReplacePhotoPlaceholders(string pattern, Dictionary<string, object> context)
        {
            var result = pattern;

            if (context.ContainsKey("Photo"))
            {
                var photo = context["Photo"] as Photo;
                if (photo != null)
                {
                    // 照片基本属性
                    result = result.Replace("{OriginalName}", System.IO.Path.GetFileNameWithoutExtension(photo.OriginalFileName));
                    result = result.Replace("{Extension}", photo.Extension);
                    result = result.Replace("{FileSize}", photo.FileSize.ToString());

                    // 照片元数据
                    if (photo.TakenTime.HasValue)
                    {
                        var takenTime = photo.TakenTime.Value;
                        result = result.Replace("{TakenDate}", takenTime.ToString("yyyy-MM-dd"));
                        result = result.Replace("{TakenTime}", takenTime.ToString("HH-mm-ss"));
                        result = result.Replace("{TakenDateTime}", takenTime.ToString("yyyy-MM-dd_HH-mm-ss"));
                    }

                    // 地理位置
                    if (photo.Location != null && !string.IsNullOrEmpty(photo.Location.City))
                    {
                        result = result.Replace("{City}", SanitizeFileName(photo.Location.City));
                    }

                    // 相机信息
                    if (photo.Metadata?.CameraMake != null)
                    {
                        result = result.Replace("{CameraMake}", SanitizeFileName(photo.Metadata.CameraMake));
                    }
                    if (photo.Metadata?.CameraModel != null)
                    {
                        result = result.Replace("{CameraModel}", SanitizeFileName(photo.Metadata.CameraModel));
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 替换自定义占位符
        /// </summary>
        private string ReplaceCustomPlaceholders(string pattern, Dictionary<string, object> context)
        {
            var result = pattern;

            foreach (var kvp in context)
            {
                if (kvp.Key.StartsWith("Custom_"))
                {
                    var placeholder = $"{{{kvp.Key.Substring(7)}}}";
                    var value = kvp.Value?.ToString() ?? "";
                    result = result.Replace(placeholder, SanitizeFileName(value));
                }
            }

            return result;
        }

        /// <summary>
        /// 替换序列号占位符
        /// </summary>
        private string ReplaceSequencePlaceholders(string pattern, Dictionary<string, object> context)
        {
            var result = pattern;

            // 序列号占位符 {Seq:起始值:步长:位数}
            var seqPattern = @"\{Seq:(\d+):(\d+):(\d+)\}";
            var matches = Regex.Matches(result, seqPattern);

            foreach (Match match in matches)
            {
                var startValue = int.Parse(match.Groups[1].Value);
                var step = int.Parse(match.Groups[2].Value);
                var digits = int.Parse(match.Groups[3].Value);

                var sequenceNumber = startValue;
                if (context.ContainsKey("SequenceNumber"))
                {
                    sequenceNumber = (int)context["SequenceNumber"];
                }

                var formattedNumber = sequenceNumber.ToString().PadLeft(digits, '0');
                result = result.Replace(match.Value, formattedNumber);
            }

            // 简单序列号占位符 {Seq}
            if (result.Contains("{Seq}") && context.ContainsKey("SequenceNumber"))
            {
                var sequenceNumber = (int)context["SequenceNumber"];
                result = result.Replace("{Seq}", sequenceNumber.ToString());
            }

            return result;
        }

        /// <summary>
        /// 应用格式化规则
        /// </summary>
        private string ApplyFormattingRules(string fileName)
        {
            var result = fileName;

            // 应用大小写规则
            result = ApplyCaseRules(result);

            // 应用分隔符规则
            result = ApplySeparatorRules(result);

            return result;
        }

        /// <summary>
        /// 应用大小写规则
        /// </summary>
        private string ApplyCaseRules(string fileName)
        {
            if (Parameters.TryGetValue("CaseRule", out var caseRuleObj) &&
                Enum.TryParse<CaseRule>(caseRuleObj.ToString(), out var caseRule))
            {
                return caseRule switch
                {
                    CaseRule.UpperCase => fileName.ToUpper(),
                    CaseRule.LowerCase => fileName.ToLower(),
                    CaseRule.TitleCase => ToTitleCase(fileName),
                    CaseRule.PascalCase => ToPascalCase(fileName),
                    CaseRule.CamelCase => ToCamelCase(fileName),
                    _ => fileName
                };
            }

            return fileName;
        }

        /// <summary>
        /// 应用分隔符规则
        /// </summary>
        private string ApplySeparatorRules(string fileName)
        {
            if (Parameters.TryGetValue("Separator", out var separatorObj))
            {
                var separator = separatorObj.ToString();
                // 替换多个连续的分隔符为单个
                var pattern = $"[{Regex.Escape(separator)}]+";
                fileName = Regex.Replace(fileName, pattern, separator);
            }

            return fileName;
        }

        /// <summary>
        /// 确保文件名唯一
        /// </summary>
        private string EnsureUniqueFileName(string fileName)
        {
            var baseName = System.IO.Path.GetFileNameWithoutExtension(fileName);
            var extension = System.IO.Path.GetExtension(fileName);
            var uniqueName = fileName;

            // 这里应该检查文件是否已存在，如果存在则根据冲突处理策略处理
            // 实际实现需要在应用服务层进行文件系统检查

            return uniqueName;
        }

        /// <summary>
        /// 验证新文件名
        /// </summary>
        private void ValidateNewFileName()
        {
            if (string.IsNullOrWhiteSpace(NewFileName))
                throw new InvalidOperationException("新文件名不能为空");

            // 检查非法字符
            var invalidChars = System.IO.Path.GetInvalidFileNameChars();
            if (NewFileName.IndexOfAny(invalidChars) >= 0)
                throw new InvalidOperationException("文件名包含非法字符");

            // 检查长度限制
            if (NewFileName.Length > 255)
                throw new InvalidOperationException("文件名过长");

            // 检查是否为保留名称
            var reservedNames = new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
            var nameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(NewFileName).ToUpper();
            if (Array.Contains(reservedNames, nameWithoutExt))
                throw new InvalidOperationException("文件名为系统保留名称");
        }

        /// <summary>
        /// 创建备份
        /// </summary>
        private void CreateBackup()
        {
            // 实际备份操作在应用服务层实现
            AddHistory(RenamingAction.BackupCreated, $"创建备份: {BackupPath}");
        }

        /// <summary>
        /// 执行重命名
        /// </summary>
        private void ExecuteRenaming()
        {
            // 实际重命名操作在应用服务层实现
            AddHistory(RenamingAction.Executed, $"执行重命名: {OriginalFileName} -> {NewFileName}");
        }

        /// <summary>
        /// 恢复原始文件名
        /// </summary>
        private void RestoreOriginalFileName()
        {
            // 实际恢复操作在应用服务层实现
            AddHistory(RenamingAction.Restored, $"恢复原始文件名: {OriginalFileName}");
        }

        /// <summary>
        /// 清理文件名
        /// </summary>
        private string ValidateAndCleanFileName(string fileName)
        {
            // 移除非法字符
            var invalidChars = System.IO.Path.GetInvalidFileNameChars();
            var cleaned = new string(fileName.Where(c => !invalidChars.Contains(c)).ToArray());

            // 移除多余的空格和点
            cleaned = Regex.Replace(cleaned, @"\s+", " ");
            cleaned = Regex.Replace(cleaned, @"\.{2,}", ".");

            // 确保不以点结尾
            cleaned = cleaned.TrimEnd('.');

            return cleaned;
        }

        /// <summary>
        /// 清理文件名中的特殊字符
        /// </summary>
        private string SanitizeFileName(string input)
        {
            if (string.IsNullOrEmpty(input))
                return "";

            var invalidChars = System.IO.Path.GetInvalidFileNameChars();
            return new string(input.Where(c => !invalidChars.Contains(c)).ToArray());
        }

        /// <summary>
        /// 转换为标题格式
        /// </summary>
        private string ToTitleCase(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            var words = input.Split(new[] { ' ', '-', '_' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length > 0)
                {
                    words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower();
                }
            }

            return string.Join(" ", words);
        }

        /// <summary>
        /// 转换为Pascal格式
        /// </summary>
        private string ToPascalCase(string input)
        {
            var titleCase = ToTitleCase(input);
            return titleCase.Replace(" ", "");
        }

        /// <summary>
        /// 转换为Camel格式
        /// </summary>
        private string ToCamelCase(string input)
        {
            var pascalCase = ToPascalCase(input);
            if (pascalCase.Length > 0)
            {
                return char.ToLower(pascalCase[0]) + pascalCase.Substring(1);
            }
            return pascalCase;
        }

        /// <summary>
        /// 添加历史记录
        /// </summary>
        private void AddHistory(RenamingAction action, string description)
        {
            var history = new RenamingHistory
            {
                Action = action,
                Description = description,
                ActionTime = DateTime.Now
            };

            History.Add(history);
        }

        /// <summary>
        /// 检查是否可以应用重命名
        /// </summary>
        public virtual bool CanApply()
        {
            return Status == RenamingStatus.Generated || Status == RenamingStatus.Preview;
        }

        /// <summary>
        /// 检查是否可以撤销
        /// </summary>
        public virtual bool CanUndo()
        {
            return Status == RenamingStatus.Completed && BackupOriginal;
        }

        /// <summary>
        /// 获取重命名预览
        /// </summary>
        public virtual RenamingPreview GetPreview()
        {
            return new RenamingPreview
            {
                OriginalFileName = OriginalFileName,
                NewFileName = NewFileName,
                Status = Status,
                Rule = Rule,
                Parameters = Parameters,
                CanApply = CanApply(),
                CanUndo = CanUndo(),
                EstimatedConflicts = EstimateConflicts()
            };
        }

        /// <summary>
        /// 估计可能的冲突数量
        /// </summary>
        private int EstimateConflicts()
        {
            // 这里应该检查新文件名是否与现有文件冲突
            // 实际实现需要在应用服务层进行文件系统检查
            return 0;
        }
    }

    /// <summary>
    /// 重命名状态枚举
    /// </summary>
    public enum RenamingStatus
    {
        /// <summary>
        /// 等待中
        /// </summary>
        Pending = 0,

        /// <summary>
        /// 已生成
        /// </summary>
        Generated = 1,

        /// <summary>
        /// 预览中
        /// </summary>
        Preview = 2,

        /// <summary>
        /// 已完成
        /// </summary>
        Completed = 3,

        /// <summary>
        /// 失败
        /// </summary>
        Failed = 4,

        /// <summary>
        /// 已取消
        /// </summary>
        Cancelled = 5,

        /// <summary>
        /// 已撤销
        /// </summary>
        Undone = 6
    }

    /// <summary>
    /// 重命名类型枚举
    /// </summary>
    public enum RenamingType
    {
        /// <summary>
        /// 手动重命名
        /// </summary>
        Manual = 0,

        /// <summary>
        /// 自动重命名
        /// </summary>
        Automatic = 1,

        /// <summary>
        /// 批量重命名
        /// </summary>
        Batch = 2,

        /// <summary>
        /// 规则重命名
        /// </summary>
        RuleBased = 3,

        /// <summary>
        /// 智能重命名
        /// </summary>
        Intelligent = 4,

        /// <summary>
        /// 模板重命名
        /// </summary>
        Template = 5
    }

    /// <summary>
    /// 重命名优先级枚举
    /// </summary>
    public enum RenamingPriority
    {
        /// <summary>
        /// 低优先级
        /// </summary>
        Low = 0,

        /// <summary>
        /// 普通优先级
        /// </summary>
        Normal = 1,

        /// <summary>
        /// 高优先级
        /// </summary>
        High = 2,

        /// <summary>
        /// 紧急优先级
        /// </summary>
        Urgent = 3
    }

    /// <summary>
    /// 冲突解决策略枚举
    /// </summary>
    public enum ConflictResolution
    {
        /// <summary>
        /// 跳过
        /// </summary>
        Skip = 0,

        /// <summary>
        /// 追加数字
        /// </summary>
        AppendNumber = 1,

        /// <summary>
        /// 追加时间戳
        /// </summary>
        AppendTimestamp = 2,

        /// <summary>
        /// 追加随机字符串
        /// </summary>
        AppendRandomString = 3,

        /// <summary>
        /// 覆盖
        /// </summary>
        Overwrite = 4,

        /// <summary>
        /// 重试
        /// </summary>
        Retry = 5
    }

    /// <summary>
    /// 大小写规则枚举
    /// </summary>
    public enum CaseRule
    {
        /// <summary>
        /// 保持原样
        /// </summary>
        AsIs = 0,

        /// <summary>
        /// 大写
        /// </summary>
        UpperCase = 1,

        /// <summary>
        /// 小写
        /// </summary>
        LowerCase = 2,

        /// <summary>
        /// 标题格式
        /// </summary>
        TitleCase = 3,

        /// <summary>
        /// Pascal格式
        /// </summary>
        PascalCase = 4,

        /// <summary>
        /// Camel格式
        /// </summary>
        CamelCase = 5
    }

    /// <summary>
    /// 重命名操作枚举
    /// </summary>
    public enum RenamingAction
    {
        /// <summary>
        /// 创建
        /// </summary>
        Created = 0,

        /// <summary>
        /// 生成
        /// </summary>
        Generated = 1,

        /// <summary>
        /// 预览
        /// </summary>
        Previewed = 2,

        /// <summary>
        /// 应用
        /// </summary>
        Applied = 3,

        /// <summary>
        /// 撤销
        /// </summary>
        Undone = 4,

        /// <summary>
        /// 取消
        /// </summary>
        Cancelled = 5,

        /// <summary>
        /// 失败
        /// </summary>
        Failed = 6,

        /// <summary>
        /// 备份创建
        /// </summary>
        BackupCreated = 7,

        /// <summary>
        /// 执行
        /// </summary>
        Executed = 8,

        /// <summary>
        /// 恢复
        /// </summary>
        Restored = 9
    }

    /// <summary>
    /// 重命名结果
    /// </summary>
    public class RenamingResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 新文件名
        /// </summary>
        public string NewFileName { get; set; }

        /// <summary>
        /// 重命名时间
        /// </summary>
        public DateTime? RenamingTime { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// 取消原因
        /// </summary>
        public string CancelReason { get; set; }

        /// <summary>
        /// 冲突数量
        /// </summary>
        public int ConflictCount { get; set; }

        /// <summary>
        /// 解决的冲突数量
        /// </summary>
        public int ResolvedConflictCount { get; set; }

        /// <summary>
        /// 处理时间（毫秒）
        /// </summary>
        public long ProcessingTimeMs { get; set; }

        /// <summary>
        /// 备份文件路径
        /// </summary>
        public string BackupFilePath { get; set; }
    }

    /// <summary>
    /// 重命名历史
    /// </summary>
    public class RenamingHistory
    {
        /// <summary>
        /// 操作类型
        /// </summary>
        public RenamingAction Action { get; set; }

        /// <summary>
        /// 操作描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 操作时间
        /// </summary>
        public DateTime ActionTime { get; set; }

        /// <summary>
        /// 操作者ID
        /// </summary>
        public Guid? OperatorId { get; set; }

        /// <summary>
        /// 操作者名称
        /// </summary>
        public string OperatorName { get; set; }

        /// <summary>
        /// 额外数据
        /// </summary>
        public Dictionary<string, object> AdditionalData { get; set; } = new();
    }

    /// <summary>
    /// 重命名预览
    /// </summary>
    public class RenamingPreview
    {
        /// <summary>
        /// 原始文件名
        /// </summary>
        public string OriginalFileName { get; set; }

        /// <summary>
        /// 新文件名
        /// </summary>
        public string NewFileName { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public RenamingStatus Status { get; set; }

        /// <summary>
        /// 重命名规则
        /// </summary>
        public RenamingRule Rule { get; set; }

        /// <summary>
        /// 参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 是否可以应用
        /// </summary>
        public bool CanApply { get; set; }

        /// <summary>
        /// 是否可以撤销
        /// </summary>
        public bool CanUndo { get; set; }

        /// <summary>
        /// 预估冲突数量
        /// </summary>
        public int EstimatedConflicts { get; set; }

        /// <summary>
        /// 变更摘要
        /// </summary>
        public string ChangeSummary => GetChangeSummary();

        /// <summary>
        /// 获取变更摘要
        /// </summary>
        private string GetChangeSummary()
        {
            if (string.IsNullOrEmpty(NewFileName))
                return "未生成新文件名";

            if (OriginalFileName == NewFileName)
                return "文件名未变更";

            return $"{OriginalFileName} → {NewFileName}";
        }
    }

    /// <summary>
    /// 重命名规则实体
    /// </summary>
    public class RenamingRule : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 规则名称
        /// </summary>
        [Required]
        [MaxLength(200)]
        public virtual string Name { get; protected set; }

        /// <summary>
        /// 规则描述
        /// </summary>
        [MaxLength(1000)]
        public virtual string Description { get; protected set; }

        /// <summary>
        /// 命名模式
        /// </summary>
        [Required]
        [MaxLength(1000)]
        public virtual string Pattern { get; protected set; }

        /// <summary>
        /// 规则类型
        /// </summary>
        public virtual RuleType RuleType { get; protected set; }

        /// <summary>
        /// 是否为系统规则
        /// </summary>
        public virtual bool IsSystem { get; protected set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public virtual bool IsEnabled { get; protected set; }

        /// <summary>
        /// 默认参数
        /// </summary>
        public virtual Dictionary<string, object> DefaultParameters { get; protected set; }

        /// <summary>
        /// 规则配置
        /// </summary>
        public virtual RuleConfiguration Configuration { get; protected set; }

        /// <summary>
        /// 使用统计
        /// </summary>
        public virtual RuleUsage Usage { get; protected set; }

        protected RenamingRule()
        {
            DefaultParameters = new Dictionary<string, object>();
            Configuration = new RuleConfiguration();
            Usage = new RuleUsage();
        }

        public RenamingRule(
            Guid id,
            string name,
            string pattern,
            RuleType ruleType = RuleType.Custom,
            bool isSystem = false,
            Guid? tenantId = null) : base(id)
        {
            Name = name;
            Pattern = pattern;
            RuleType = ruleType;
            IsSystem = isSystem;
            TenantId = tenantId;
            IsEnabled = true;

            DefaultParameters = new Dictionary<string, object>();
            Configuration = new RuleConfiguration();
            Usage = new RuleUsage();
        }

        /// <summary>
        /// 启用规则
        /// </summary>
        public virtual void Enable()
        {
            IsEnabled = true;
        }

        /// <summary>
        /// 禁用规则
        /// </summary>
        public virtual void Disable()
        {
            IsEnabled = false;
        }

        /// <summary>
        /// 更新模式
        /// </summary>
        public virtual void UpdatePattern(string pattern)
        {
            Pattern = pattern;
        }

        /// <summary>
        /// 更新默认参数
        /// </summary>
        public virtual void UpdateDefaultParameters(Dictionary<string, object> parameters)
        {
            DefaultParameters = parameters ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 记录使用
        /// </summary>
        public virtual void RecordUsage()
        {
            Usage.TotalUsageCount++;
            Usage.LastUsedTime = DateTime.Now;
        }

        /// <summary>
        /// 检查是否可以使用
        /// </summary>
        public virtual bool CanUse()
        {
            return IsEnabled && !string.IsNullOrEmpty(Pattern);
        }
    }

    /// <summary>
    /// 规则类型枚举
    /// </summary>
    public enum RuleType
    {
        /// <summary>
        /// 自定义规则
        /// </summary>
        Custom = 0,

        /// <summary>
        /// 系统规则
        /// </summary>
        System = 1,

        /// <summary>
        /// 日期时间规则
        /// </summary>
        DateTime = 2,

        /// <summary>
        /// 元数据规则
        /// </summary>
        Metadata = 3,

        /// <summary>
        /// 序列号规则
        /// </summary>
        Sequence = 4,

        /// <summary>
        /// 位置规则
        /// </summary>
        Location = 5,

        /// <summary>
        /// 相机规则
        /// </summary>
        Camera = 6,

        /// <summary>
        /// 事件规则
        /// </summary>
        Event = 7
    }

    /// <summary>
    /// 规则配置
    /// </summary>
    public class RuleConfiguration
    {
        /// <summary>
        /// 支持的文件类型
        /// </summary>
        public List<string> SupportedFileTypes { get; set; } = new();

        /// <summary>
        /// 排除的文件类型
        /// </summary>
        public List<string> ExcludedFileTypes { get; set; } = new();

        /// <summary>
        /// 最大文件大小（MB）
        /// </summary>
        public long MaxFileSizeMB { get; set; } = 100;

        /// <summary>
        /// 是否允许覆盖
        /// </summary>
        public bool AllowOverwrite { get; set; } = false;

        /// <summary>
        /// 默认冲突处理策略
        /// </summary>
        public ConflictResolution DefaultConflictResolution { get; set; } = ConflictResolution.AppendNumber;

        /// <summary>
        /// 是否预览模式
        /// </summary>
        public bool PreviewByDefault { get; set; } = true;

        /// <summary>
        /// 是否创建备份
        /// </summary>
        public bool CreateBackupByDefault { get; set; } = false;
    }

    /// <summary>
    /// 规则使用统计
    /// </summary>
    public class RuleUsage
    {
        /// <summary>
        /// 总使用次数
        /// </summary>
        public int TotalUsageCount { get; set; }

        /// <summary>
        /// 成功次数
        /// </summary>
        public int SuccessCount { get; set; }

        /// <summary>
        /// 失败次数
        /// </summary>
        public int FailureCount { get; set; }

        /// <summary>
        /// 最后使用时间
        /// </summary>
        public DateTime? LastUsedTime { get; set; }

        /// <summary>
        /// 使用用户列表
        /// </summary>
        public List<string> UsedByUsers { get; set; } = new();

        /// <summary>
        /// 成功率
        /// </summary>
        public double SuccessRate => TotalUsageCount > 0 ? (double)SuccessCount / TotalUsageCount : 0;
    }
}